import GCBlock from "../../components/common-components/GCBlock";
import GCToast from "../../components/common-components/GCToast";
import GameLogic from "../../GameLogic";
import GCConnection from "../../GCConnection";
import GCGlobal from "../../GCGlobal";
import GCState from "../GCState";

export class MenuState extends GCState {

    async enter(logic: GameLogic) {
        const account = GCGlobal.Account;
        // 更新用户信息
        logic.header.initUI(account.name, account.hearts, account.icon);
        // 更新三个游戏入口信息
        // TODO
        logic.menu.initUI(account.survivalCount);
        logic.header.backNode.active = true;

        if (!logic.dailyRewardWnd.requested) {
            this.getDailyReward(logic);
        }

        if (!logic.tip.tip) {
            this.getTip(logic);
        }
    }

    async getDailyReward(logic: GameLogic) {
        GCBlock.block();
        try {
            const resp = await GCConnection.requestDailyReward();

            if (resp.hearts > 0) {
                GCGlobal.Account.hearts += resp.hearts;
                logic.dailyRewardWnd.initUI(resp.hearts);
                logic.dailyRewardWnd.showWnd();
            }

            logic.dailyRewardWnd.requested = true;
        } catch (e) {
            cc.error(e);

            GCToast.toast('获取每日奖励失败');
        } finally {
            GCBlock.unblock();
        }
    }

    async getTip(logic: GameLogic) {
        GCBlock.block();
        try {
            const resp = await GCConnection.requestTip(1);
            logic.tip.initUI(resp.tip);
            logic.tip.showWnd();
        } catch (e) {
            if (e.code === 111) {
                return;
            }

            cc.error(e);

            GCToast.toast('获取温馨提示失败');
        } finally {
            GCBlock.unblock();
        }
    }

    exit(logic: GameLogic): void {
        logic.classicComp.resetUI();
    }

    process(logic: any, type: string, res?: any): void {
        if (type === 'claim-daily-reward') {
            logic.dailyRewardWnd.doClaimDailyReward(logic.header.getHeartPosInWorld(), () => {
                cc.log(`GCGlobal.Account.hearts: ${GCGlobal.Account.hearts}`);
                logic.header.updateHearts(GCGlobal.Account.hearts);
                logic.dailyRewardWnd.closeWind();
            });
        }
    }
}
